// pages/shop/join.ts
import type { queryFormState, keyDatasetState } from '~/../typings/types/shop'
import { getProvinces, getCities, getCounties } from '~/common/regions'
import { doUploadImage, doJoinInfo, doJoin } from '~/api/join'
import { back } from '~/utils/util'
import type { cityState } from '~/common/regions'
import type { itemState } from '~/../typings/types/city'
const chooseLocation = requirePlugin('chooseLocation');
let loading = false
Page({

  /**
   * 页面的初始数据
   */
  data: {
    pickKeys: {
      value: 'name',
      label: 'name'
    },
    phone: '051681812345',
    disabled: false,
    queryForm: {
      name: '',
      province: '',
      city: '',
      area: '',
      address: '',
      introduction: '',
      contact: '',
      mobile: '',
      imageUrl: '',
      businessLicenseImageUrl: '',
      serviceSite: '',
    } as queryFormState,
    areaVisible: false,
    areaValue: [],
    provinces: getProvinces(),
    cities: [] as cityState[],
    counties: [] as cityState[],
  },
  bindDestination() {
    const { queryForm } = this.data
    wx.navigateTo({
      url: `/pages/shop/destination/destination?id=${queryForm.id}`
    })
  },
  toast(title: string) {
    wx.showToast({
      icon: 'none',
      title
    })
  },
  //  提交数据
  async handSubmit() {
    const { queryForm } = this.data
    if (!queryForm.name) {
      this.toast('请输入公司名称')
      return
    }
    if (!queryForm.province) {
      this.toast('请选择公司所在区域')
      return
    }
    if (!queryForm.address) {
      this.toast('请输入公司详情地址')
      return
    }
    // if (!queryForm.introduction) {
    //   this.toast('请输入直达线路或主营的内容')
    //   return
    // }
    if (!queryForm.contact) {
      this.toast('请输入联系人姓名')
      return
    }
    if (!queryForm.mobile) {
      this.toast('请输入联系电话')
      return
    }
    if (!queryForm.serviceSite) {
      this.toast('请选择入住站点')
      return
    }
    if (loading) return
    loading = true

    try {
      await doJoin(queryForm)
      this.toast('已申请,请耐心等待')
      let timer = setTimeout(() => {
        clearTimeout(timer)
        back()
      }, 300)
    } catch (error) {
      loading = false
    }
  },
  //  上传图片
  handChoose(this: any, e: any) {
    const name: string = e.currentTarget.dataset.key
    console.log(name)
    if (this.data.disabled) {
      if (this.data.queryForm[name]) {
        wx.previewImage({
          urls: [this.data.queryForm[name]]
        })
      } else {
        wx.showToast({
          icon: 'none',
          title: '未上传'
        })
      }

      return
    }
    wx.chooseMedia({
      count: 1,
      mediaType: ['image'],
      success: (res) => {
        doUploadImage(res.tempFiles[0].tempFilePath).then((data: any) => {
          const queryForm = this.data.queryForm
          queryForm[name] = data.url
          this.setData({
            queryForm
          })
        })
      }
    })
  },
  //  入住站点
  handJoin() {
    if (this.data.disabled) return
    wx.navigateTo({
      url: '/pages/city/index?type=homeTop',
      events: {
        chooseEvent: (e: itemState[]) => {
          const info = e[e.length - 1]
          const { queryForm } = this.data
          queryForm.serviceSite = e.map((el: itemState) => {
            return el.label
          }).join('-')
          this.setData({
            info,
            phone: info.description,
            queryForm
          })
        }
      }
    })
  },
  //  拨号
  handCall() {
    wx.makePhoneCall({
      phoneNumber: this.data.phone
    })
  },
  // 省市区
  onColumnChange(e: any) {
    const { column, index } = e.detail;
    const { provinces, cities } = this.data;
    if (column === 0) {
      const cities = getCities(provinces[index].name);
      const counties = getCounties(provinces[index].name, cities[0].name)
      this.setData({ cities, counties });
    }
    if (column === 1) {
      const info = cities[index]
      if (info && info?.name) {
        const counties = getCounties(e.detail.value[0], info?.name)
        this.setData({ counties });
      }

    }
  },
  onPickerChange(e: any) {
    const { value } = e.detail;
    const queryForm = this.data.queryForm
    queryForm.province = value[0]
    queryForm.city = value[1]
    queryForm.area = value[2]
    this.setData({
      queryForm,
      areaValue: value
    });
  },
  onPickerCancel() {
    this.setData({
      areaVisible: false,
    });
  },
  onAreaPicker(this: any) {
    if (this.data.disabled) return
    const key = 'J2LBZ-5HJKJ-MQVFF-XNIJJ-JK7BZ-4IB6R'; //使用在腾讯位置服务申请的key
    const referer = '运友物流专线查询平台'
    wx.navigateTo({
      url: `plugin://chooseLocation/index?key=${key}&referer=${referer}`
    })
    // wx.chooseLocation({
    //   success: (res) => {
    //     console.log(res)
    //   },
    //   fail: (err) => {
    //     console.log(err)
    //     wx.showToast({
    //       icon: 'none',
    //       title: err.errMsg
    //     })
    //   }
    // })
    // this.setData({ areaVisible: true });
  },
  // input 双向绑定
  bindKeyInput(e: WechatMiniprogram.Input) {
    const key: keyDatasetState = e.currentTarget.dataset.params
    const { queryForm } = this.data
    queryForm[key] = e.detail.value
    if (this.data.queryForm) {
      this.setData({
        queryForm
      })
    }
  },
  /**
   * 生命周期函数--监听页面加载
   */
  async onLoad() {
    const data = await doJoinInfo()
    if (data) {
      this.setData({
        queryForm: data,
        disabled: [1, 4].includes(data.status)
      })
    }
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {
    const { provinces } = this.data;
    const cities = getCities(provinces[0].name);
    const counties = getCounties(provinces[0].name, cities[0].name)
    this.setData({ cities, counties });
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    const location = chooseLocation.getLocation(); // 如果点击确认选点按钮，则返回选点结果对象，否则返回null
    if (location) {
      const { province, city, district, name, latitude, longitude } = location
      const { queryForm } = this.data
      this.setData({
        queryForm: {
          ...queryForm,
          province,
          city,
          area: district,
          address: name,
          lat: latitude,
          lng: longitude
        }
      });

    }
    console.log(location)
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {
    // 页面卸载时设置插件选点数据为null，防止再次进入页面，geLocation返回的是上次选点结果
    chooseLocation.setLocation(null);
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})